import requests
from urllib import parse
import json
import re


def _replace_argument(target_str, arguments):
    """
    定义私有函数，用来替换包含{{}}的参数
    :param target_str:
    :param arguments:
    :return:
    """
    # {"project_id":2,"token":"xxxxx"}
    # /project/{{project_id}}/{{api_id}}
    if not arguments:
        return target_str
    while True:
        search_result = re.search(r"{{(.+?)}}", target_str)
        if not search_result:
            break
        argument_name = search_result.group(1)
        if argument_name in arguments:
            target_str = re.sub("{{" + argument_name + "}}", str(arguments[argument_name]), target_str)
        else:
            target_str = re.sub("{{" + argument_name + "}}", argument_name, target_str)
    return target_str


def request(api, arguments=None):
    # 获取域名，就是我们添加到数据库中的host
    host = api.host.host
    # 获取请求方法
    method = api.http_method
    # 获取请求路径
    path = api.path
    # host:http://www.baidu.com/
    # path: /q?wd=python
    # http://www.baidu.com/q?wd=python
    url = parse.urljoin(host, path)  # 拼接url
    url = _replace_argument(url, arguments)  # 判断前端传入的数据是否包含{{}}，有的话就替换
    # 定义请求参数，循环api.data中的数据添加到data中
    data = {}
    if api.data:
        data_list = json.loads(api.data)
        for data_dict in data_list:
            # [{name:"username",value:"lingxi"}]
            data[data_dict['name']] = _replace_argument(data_dict['value'], arguments)
    # 定义请求头，循环api.headers中的数据，添加到headers中
    headers = {}
    if api.headers:
        header_list = json.loads(api.headers)
        for header_dict in header_list:
            headers[header_dict['name']] = _replace_argument(header_dict['value'], arguments)
    # 发送请求，返回响应数据
    resp = requests.request(method, url, headers=headers, data=data)
    return resp
